package com.test.qpbgboot.base.rabbitmq;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class RabbitMQProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private static final Map<String, Integer> failMap = new HashMap<>();

    @PostConstruct
    public void setRabbitTemplate() {
        //设置消息发送的确认回调类
        rabbitTemplate.setConfirmCallback(((correlationData, ack, cause) -> {
            if (ack) {
                log.debug("发送-消息-给RabbitMQ队列-成功");
            } else {
                log.warn("发送-消息-给RabbitMQ队列-失败 cause:{}", cause);
            }
        }));
    }

    public void send(String message, String exchange, String routingKey) {
        log.debug("发送-消息-给RabbitMQ队列 message:{},exchange:{},routingKey:{}",
                message, exchange, routingKey);
        //消息持久化
        Message enMessage = new Message(message.getBytes(), new MessageProperties());
        enMessage.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
        rabbitTemplate.convertAndSend(exchange, routingKey, enMessage);
    }
}
